package com.example.mobile2021606128wje0618;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

public class MyDataAdpter {
    private MySQLiteOpenHelper openHelper;
    private SQLiteDatabase database;
    public void openDB(Context context){
        //创建数据库对象
        openHelper=new MySQLiteOpenHelper(context,"student.db",null,1);
        try{
            database=openHelper.getWritableDatabase();
        }catch (Exception e){
            database=openHelper.getReadableDatabase();
        }
    }
    public void closeDB(){
        if (database!=null){
            database.close();
            database=null;
        }
        if (openHelper!=null){
            openHelper.close();
            openHelper=null;
        }
    }
    public List<Student> QueryAll(Context context) {
        List<Student> studentList = new ArrayList<>();
        openDB(context);
        Cursor cursor = database.query("student", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                int id = cursor.getInt(0);
                String name = cursor.getString(1);
                int age = cursor.getInt(2);
                float score = cursor.getFloat(3);
                studentList.add(new Student(id, name, age, score));

            } while (cursor.moveToNext());
        }
        cursor.close();
        closeDB();
        return studentList;
    }
    public long insert(Context context,Student student){
        openDB(context);
        ContentValues values=new ContentValues();
        values.put("name",student.getName());
        values.put("age",student.getAge());
        values.put("score",student.getScore());
        long result = database.insert("student",null,values);
        closeDB();
        return  result;
    }
    public int delete(Context context,int id){
        openDB(context);
        int result=database.delete("student","_id?",new String[]{String.valueOf(id)});
        closeDB();
        return result;
    }
    public int update(Context context,int id,Student student){
        openDB(context);
        ContentValues values=new ContentValues();
        values.put("name",student.getName());
        values.put("age",student.getAge());
        values.put("score",student.getScore());
        int result =database.update("student",values,"_id?",new String[]{String.valueOf(id)});
        closeDB();;
        return result;
    }
}
